<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>06_组件实例三大属性1_state</title>
    <script src="https://lf26-cdn-tos.bytecdntp.com/cdn/expire-1-M/react/18.2.0/umd/react.production.min.js"></script>
    <script src="https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/react-dom/18.2.0/umd/react-dom.production.min.js"></script>
    <script src="https://lf9-cdn-tos.bytecdntp.com/cdn/expire-1-M/babel-standalone/6.26.0/babel.min.js"></script>
  </head>

  /**
    * 1.创建组件
    * 2.初始化state基础属性
    * 3.通过点击事件修改state的值
    * 4.使用setState来修改state的值, 并通过点击来停止定时器的触发,, 停止和触发来进行字段
    */
  <body>
    <div id="test"></div>
    <script type="text/babel">
      class Counter extends React.Component {
        constructor(props) {
          super(props);
        }
        // 组件挂载完成后启动定时器
        componentDidMount() {
          this.timer = setInterval(() => {
            this.setState((state) => ({
              count: state.count + 1,
            }));
          }, 1000);
        }

        // 组件更新时触发
        componentDidUpdate(prevProps, prevState) {
          // 检查count是否发生变化
          if (this.state.count !== prevState.count) {
            console.log('计数器更新了:', this.state.count);
          }
          // 检查暂停状态是否发生变化
          if (this.state.isPaused !== prevState.isPaused) {
            console.log('暂停状态更新为:', this.state.isPaused);
          }
        }

        // 组件卸载前清除定时器
        componentWillUnmount() {
          clearInterval(this.timer);
        }
        // 添加暂停状态
        state = {
          count: 0,
          isPaused: false,
        };

        // 处理按钮点击事件, setState 是异步的，需要使用回调函数来获取最新的状态
        handleClick = () => {
          this.setState(
            (state) => ({
              isPaused: !state.isPaused,
            }),
            // 回调函数
            () => {
              if (this.state.isPaused) {
                // 暂停时清除定时器
                clearInterval(this.timer);
              } else {
                // 继续时重新启动定时器
                this.timer = setInterval(() => {
                  this.setState((state) => ({
                    count: state.count + 1,
                  }));
                }, 1000);
              }
            }
          );
        };

        render() {
          return (
            <div>
              <h1>当前计数：{this.state.count}</h1>
              <button onClick={this.handleClick}>点我</button>
            </div>
          );
        }
      }
      const root = ReactDOM.createRoot(document.getElementById("test"));
      root.render(<Counter />);
    </script>
  </body>
</html>
